
package com.kugou.game.sdk.utils;

import com.kugou.framework.base.LogUtil;
import com.kugou.game.sdk.api.common.OnExitListener;
import com.kugou.game.sdk.core.FolderManager;
import com.kugou.game.sdk.core.PlatformEventDispatcher;
import com.kugou.game.sdk.entity.AdInfo;
import com.kugou.game.sdk.protocol.AdTask;
import com.kugou.game.sdk.protocol.AdTask.AdResponse;
import com.kugou.game.sdk.statistics.StatCmd;
import com.kugou.game.sdk.statistics.StaticsManager;
import com.kugou.game.sdk.ui.activity.GameCenterActivity;
import com.kugou.game.sdk.ui.dialog.ExitAdDialog;
import com.kugou.game.sdk.ui.widget.AdView;
import com.kugou.game.sdk.utils.AsyncImageLoader.ImageCallback;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Application;
import android.content.ComponentName;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.FrameLayout;
import android.widget.ImageView;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 描述:广告管理类
 * 
 * @author liux
 * @since 2015-3-13 下午3:02:58
 */
public class AdHelper {
    private Activity mActivity;

    private AsyncImageLoader mAsyncImageLoader;

    private static AdHelper adHelper;

    // 随机选中的定时广告信息
    private AdInfo ad1Info;

    // 随机选中的弹窗广告信息
    private AdInfo ad2Info;

    private AdHelper(Activity activity) {
        this.mActivity = activity;
        this.mAsyncImageLoader = new AsyncImageLoader();
    }

    public static AdHelper getInstance(Activity activity) {
        if (adHelper == null) {
            synchronized (AdHelper.class) {
                if (adHelper == null) {
                    adHelper = new AdHelper(activity);
                }
            }
        }
        return adHelper;
    }

    /**
     * 请求广告信息
     */
    public void requestAdInfo() {
        ThreadTaskManager.excuteTask(new Runnable() {
            public void run() {
                AdTask task = new AdTask();
                AdResponse response = task.request();
                if (response != null && response.isOk()) {
                    // 标记请求广告信息成功
                    if (!isLoadAdInfoOk()) {
                        setLoadAdInfoOk(true);
                    }

                    // 处理定时广告返回结果
                    ArrayList<AdInfo> adlList = response.getAd1List();
                    ad1Info = handAdTaskResult(adlList, 1);
                    // 处理弹窗广告返回结果
                    ArrayList<AdInfo> ad2List = response.getAd2List();
                    ad2Info = handAdTaskResult(ad2List, 2);
                }
            }
        });
    }

    /**
     * 处理广告结果信息
     * 
     * @param context
     * @param adList
     * @param adType 1:定时 2：弹窗
     */
    private AdInfo handAdTaskResult(ArrayList<AdInfo> adList, final int adType) {
        if (adList != null && adList.size() > 0) {
            int size = adList.size();
            Random random = new Random();
            // 随机获取广告任务中的一个
            int index = random.nextInt(size);
            final AdInfo ad = adList.get(index);
            LogUtil.d("dax", "adType->" + adType + "--size-->" + size + "--index-->" + index);
            // 预加载广告图片
            String iconUrl = ad.getAdImageUrl();
            String imgKey = iconUrl + adType;
            String savePath = FolderManager.IMAGE_CACHE_FOLDER
                    + AppUtil.getFileNameFromUrl(iconUrl);
            Bitmap bitmap = mAsyncImageLoader.loadImage(mActivity, imgKey, iconUrl, savePath,
                    new ImageCallback() {
                        public void imageLoaded(Bitmap bitmap, String key) {
                            if (bitmap != null) {
                                setAdImagePreloadResultOk(adType, ad);
                            }
                        }
                    });
            if (bitmap != null) {
                setAdImagePreloadResultOk(adType, ad);
            }
            return ad;
        }
        return null;
    }

    /**
     * 设置广告图片预加载成功
     * 
     * @param adType
     */
    private void setAdImagePreloadResultOk(int adType, final AdInfo ad) {
        if (adType == 1) {// 定时广告
            setPreloadAd1Ok(true);
            // 根据后台配置的间隔时长(单位：秒)，显示定时广告
            int span = ad.getAdShowTimeSpan();
            LogUtil.d("dax", "定时广告预加载OK---间隔：" + span);
            PlatformEventDispatcher.runOnUiThreadDelayed(new Runnable() {
                public void run() {
                    // showFixedTimeAd(ad);
                    try {
                        showFixedTimeAd_v2(ad);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    // 监测当前应用是否在前台
                    // monitorAppForgroundState(ad);
                }
            }, span * 1000);
        } else if (adType == 2) {// 弹窗广告
            LogUtil.d("dax", "弹窗广告预加载OK");
            setPreloadAd2Ok(true);
        }
    }

    /** 应用是否退出 */
    private boolean appExit = false;

    /** 定时广告是否已经点击关闭 */
    private boolean closedBottomAd = false;

    /** 定时广告是否正在展示 */
    private boolean isBottomAdShowing = false;

    /**
     * 监测当前应用是否在前台
     */
    protected void monitorAppForgroundState(final AdInfo ad) {
        ThreadTaskManager.excuteTask(new Runnable() {
            public void run() {
                if (isPreloadAd1Ok() && ad != null) {
                    while (!closedBottomAd && !appExit) {
                        try {
                            PlatformEventDispatcher.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (isRunningForeground()) {
                                        if (!isBottomAdShowing) {
                                            showFixedTimeAd(ad);
                                        }
                                    } else {
                                        closeBottomAd();
                                    }
                                }
                            });

                            Thread.sleep(500);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
    }

    LayoutParams wmParams;

    WindowManager mWindowManager;

    View ad1LayoutView;

    /**
     * 显示定时广告
     */
    private void showFixedTimeAd(AdInfo ad) {
        wmParams = new LayoutParams();
        mWindowManager = (WindowManager) mActivity.getSystemService(Application.WINDOW_SERVICE);
        wmParams.type = LayoutParams.TYPE_APPLICATION;
        wmParams.format = PixelFormat.RGBA_8888;
        wmParams.flags = LayoutParams.FLAG_NOT_FOCUSABLE | LayoutParams.FLAG_NOT_TOUCH_MODAL;
        wmParams.gravity = Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM;
        wmParams.x = 0;
        wmParams.y = 0;

        wmParams.width = LayoutParams.MATCH_PARENT;
        wmParams.height = LayoutParams.WRAP_CONTENT;

        int adResId = Rx.layout.kg_single_bottom_ad_layout;
        ad1LayoutView = LayoutInflater.from(mActivity).inflate(adResId, null);
        ImageView adShowImg = (ImageView) ad1LayoutView.findViewById(Rx.id.kg_single_bottom_ad_img);
        ImageView adCloseImg = (ImageView) ad1LayoutView
                .findViewById(Rx.id.kg_single_bottom_ad_close_btn);

        if (isPreloadAd1Ok() && ad != null) {
            String iconUrl = ad.getAdImageUrl();
            String imgKey = iconUrl;
            String savePath = FolderManager.IMAGE_CACHE_FOLDER
                    + AppUtil.getFileNameFromUrl(iconUrl);
            Bitmap ad1Img = mAsyncImageLoader.loadImage(mActivity, imgKey, iconUrl, savePath, null);
            if (ad1Img != null) {
                adShowImg.setImageBitmap(ad1Img);
                adShowImg.setOnClickListener(new Ad1Listener(ad));
                adCloseImg.setOnClickListener(new Ad1Listener(ad));
                mWindowManager.addView(ad1LayoutView, wmParams);

                // 发送定时广告统计--展示
                int adid = ad.getAdId();
                StaticsManager.sendSinleAdStatics(StatCmd.CMD_SINGLE_AD_SHOW, 1, adid);

                isBottomAdShowing = true;
            }
        }
    }

    /**
     * 关闭定时广告
     */
    private void closeBottomAd() {
        try {
            if (mWindowManager != null && ad1LayoutView != null) {
                mWindowManager.removeView(ad1LayoutView);
                isBottomAdShowing = false;
            }
        } catch (Exception e) {
            isBottomAdShowing = false;
        }
    }

    /**
     * 当前应用是否在前台显示
     * 
     * @return
     */
    public boolean isRunningForeground() {
        String packageName = mActivity.getPackageName();
        String topActivityClassName = getTopActivityName(mActivity);
        if (packageName != null && topActivityClassName != null
                && topActivityClassName.startsWith(packageName)) {
            return true;
        } else {
            return false;
        }
    }

    private String getTopActivityName(Context context) {
        String topActivityClassName = null;
        ActivityManager activityManager = (ActivityManager) (context
                .getSystemService(Context.ACTIVITY_SERVICE));
        List<RunningTaskInfo> runningTaskInfos = activityManager.getRunningTasks(1);
        if (runningTaskInfos != null) {
            ComponentName f = runningTaskInfos.get(0).topActivity;
            topActivityClassName = f.getClassName();
        }
        return topActivityClassName;
    }

    /**
     * 描述:定时广告点击监听器
     * 
     * @author liux
     * @since 2015-3-17 下午3:13:37
     */
    class Ad1Listener implements OnClickListener {
        AdInfo ad;

        public Ad1Listener(AdInfo ad) {
            this.ad = ad;
        }

        public void onClick(View v) {
            int id = v.getId();
            if (id == Rx.id.kg_single_bottom_ad_img) {// 定时广告图片
                if (ad != null) {
                    // 打开系统浏览器加载链接
                    String link = ad.getAdLinkUrl();
                    AppUtil.openSystemBrowser(mActivity, link);

                    // 发送定时广告统计--点击
                    int adid = ad.getAdId();
                    StaticsManager.sendSinleAdStatics(StatCmd.CMD_SINGLE_AD_CLICK, 1, adid);
                }
            }
            // 关闭定时广告
            // closeBottomAd();
            closeBottonAd_v2();
            closedBottomAd = true;
        }
    }

    /**
     * 默认弹窗广告的点击链接地址
     */
    private static final String DEFAULT_AD_LINK_URL = GameCenterActivity.MAIN_PAGE_URL
            + "&businessid=3";

    /**
     * 显示退出（弹窗）广告
     */
    public void showExitAdDialog(Activity activity, final OnExitListener listener) {
        final ExitAdDialog dialog = new ExitAdDialog(activity);
        dialog.setCancelBtnText("再玩一会");
        dialog.setOkBtnText("狠心退出");
        dialog.setTitle("要退出游戏了吗？");
        dialog.setTitleGravity(Gravity.CENTER);
        dialog.setCloseImgVisibility(false);

        if (ad2Info != null && isPreloadAd2Ok()) {
            String iconUrl = ad2Info.getAdImageUrl();
            String imgKey = iconUrl;
            String savePath = FolderManager.IMAGE_CACHE_FOLDER
                    + AppUtil.getFileNameFromUrl(iconUrl);
            Bitmap ad1Img = mAsyncImageLoader.loadImage(mActivity, imgKey, iconUrl, savePath, null);
            if (ad1Img != null) {
                dialog.setImageBitmap(ad1Img);
                dialog.setImageClickListener(new OnClickListener() {
                    public void onClick(View v) {
                        if (dialog != null) {
                            dialog.dismiss();
                        }
                        String url = ad2Info.getAdLinkUrl();
                        AppUtil.openSystemBrowser(mActivity, url);
                        // 发送弹窗广告统计（后台配置的广告）--点击
                        int adid = ad2Info.getAdId();
                        StaticsManager.sendSinleAdStatics(StatCmd.CMD_SINGLE_AD_CLICK, 2, adid);
                    }
                });
            } else {
                // 设置默认的广告图片
                dialog.setImageResource(Rx.drawable.kg_single_ad_dialog_bg_default);
                dialog.setImageClickListener(new OnClickListener() {
                    public void onClick(View v) {
                        if (dialog != null) {
                            dialog.dismiss();
                        }
                        // 进入默认链接地址，
                        AppUtil.openSystemBrowser(mActivity, DEFAULT_AD_LINK_URL);

                        // 发送弹窗广告统计（客户端默认的广告。默认广告id为0）--点击
                        StaticsManager.sendSinleAdStatics(StatCmd.CMD_SINGLE_AD_CLICK, 2, 0);
                    }
                });
            }
        } else {
            // 设置默认的广告图片
            dialog.setImageResource(Rx.drawable.kg_single_ad_dialog_bg_default);
            dialog.setImageClickListener(new OnClickListener() {
                public void onClick(View v) {
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                    // 进入默认链接地址，
                    AppUtil.openSystemBrowser(mActivity, DEFAULT_AD_LINK_URL);

                    // 发送弹窗广告统计（客户端默认的广告。默认广告id为0）--点击
                    StaticsManager.sendSinleAdStatics(StatCmd.CMD_SINGLE_AD_CLICK, 2, 0);
                }
            });
        }
        // 点击"退出游戏"
        dialog.setOKClickListener(new OnClickListener() {
            public void onClick(View v) {
                if (dialog != null) {
                    dialog.dismiss();
                }

                if (listener != null) {
                    try {
                        listener.exitGame(0);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                appExit = true;
            }
        });
        // 点击"再玩一会"
        dialog.setCancelClickListener(new OnClickListener() {
            public void onClick(View v) {
                if (dialog != null) {
                    dialog.dismiss();
                }
            }
        });
        dialog.show();
        // 发送弹窗广告统计--展示
        if (ad2Info != null && isPreloadAd2Ok()) {
            int adid = ad2Info.getAdId();
            StaticsManager.sendSinleAdStatics(StatCmd.CMD_SINGLE_AD_SHOW, 2, adid);
        } else {
            // 默认广告id为0
            StaticsManager.sendSinleAdStatics(StatCmd.CMD_SINGLE_AD_SHOW, 2, 0);
        }
    }

    /** 预加载定时广告图片是否成功 */
    private boolean preloadAd1Ok = false;

    /** 预加载弹窗广告图片是否成功 */
    private boolean preloadAd2Ok = false;

    /** 请求广告信息是否成功 */
    private boolean loadAdInfoOk = false;

    public boolean isPreloadAd1Ok() {
        return preloadAd1Ok;
    }

    public void setPreloadAd1Ok(boolean preloadAd1Ok) {
        this.preloadAd1Ok = preloadAd1Ok;
    }

    public boolean isPreloadAd2Ok() {
        return preloadAd2Ok;
    }

    public void setPreloadAd2Ok(boolean preloadAd2Ok) {
        this.preloadAd2Ok = preloadAd2Ok;
    }

    public boolean isLoadAdInfoOk() {
        return loadAdInfoOk;
    }

    public void setLoadAdInfoOk(boolean loadAdInfoOk) {
        this.loadAdInfoOk = loadAdInfoOk;
    }

    FrameLayout viewGroup = null;

    AdView adView = null;

    protected void showFixedTimeAd_v2(final AdInfo ad) {
        if (mActivity != null && !mActivity.isFinishing()) {
            viewGroup = (FrameLayout) mActivity.findViewById(android.R.id.content);
            if (viewGroup != null) {
                adView = new AdView(mActivity);
                if (isPreloadAd1Ok() && ad != null) {
                    String iconUrl = ad.getAdImageUrl();
                    String imgKey = iconUrl;
                    String savePath = FolderManager.IMAGE_CACHE_FOLDER
                            + AppUtil.getFileNameFromUrl(iconUrl);
                    Bitmap ad1Img = mAsyncImageLoader.loadImage(mActivity, imgKey, iconUrl,
                            savePath, null);
                    if (ad1Img != null) {
                        adView.setImageBitmap(ad1Img);
                        adView.setOnAdShowImgClickListener(new OnClickListener() {
                            public void onClick(View view) {
                                Log.d("dax", "setOnAdShowImgClickListener");
                                // 打开系统浏览器加载链接
                                String link = ad.getAdLinkUrl();
                                AppUtil.openSystemBrowser(mActivity, link);

                                // 发送定时广告统计--点击
                                int adid = ad.getAdId();
                                StaticsManager.sendSinleAdStatics(StatCmd.CMD_SINGLE_AD_CLICK, 1,
                                        adid);

                                // 关闭定时广告
                                closeBottonAd_v2();
                            }

                        });
                        adView.setOnAdCloseImgClickListener(new OnClickListener() {
                            public void onClick(View view) {
                                Log.d("dax", "setOnAdCloseImgClickListener");
                                // 关闭定时广告
                                closeBottonAd_v2();
                            }

                        });

                        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                                FrameLayout.LayoutParams.MATCH_PARENT,
                                FrameLayout.LayoutParams.WRAP_CONTENT);
                        params.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
                        adView.setLayoutParams(params);
                        viewGroup.addView(adView);

                        // 发送定时广告统计--展示
                        int adid = ad.getAdId();
                        StaticsManager.sendSinleAdStatics(StatCmd.CMD_SINGLE_AD_SHOW, 1, adid);
                        isBottomAdShowing = true;
                    }
                }
            }
        }

    }

    public void closeBottonAd_v2() {
        try {
            if (viewGroup != null && adView != null) {
                viewGroup.removeView(adView);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
